<template>
  <div class="home-container">
    <el-container>
      <!-- 顶部导航 -->
      <el-header class="header">
        <div class="header-left">
          <h2>YY云盘</h2>
        </div>
        <div class="header-right">
          <el-dropdown @command="handleCommand">
            <span class="user-info">
              <el-icon><User /></el-icon>
              {{ userStore.userInfo?.nickname || '用户' }}
              <el-icon><ArrowDown /></el-icon>
            </span>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="profile">个人信息</el-dropdown-item>
                <el-dropdown-item command="logout" divided>退出登录</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </el-header>

      <el-container>
        <!-- 侧边栏 -->
        <el-aside width="150px" class="sidebar">
          <el-menu
            :default-active="$route.path"
            router
            background-color="#f5f5f5"
            text-color="#333"
            active-text-color="#409eff"
          >
            <el-menu-item index="/files">
              <el-icon><Folder /></el-icon>
              <span>我的文件</span>
            </el-menu-item>
            <el-menu-item index="/uploads">
              <el-icon><Upload /></el-icon>
              <span>上传列表</span>
            </el-menu-item>
            <el-menu-item index="/share">
              <el-icon><Share /></el-icon>
              <span>我的分享</span>
            </el-menu-item>
            <el-menu-item index="/recycle">
              <el-icon><Delete /></el-icon>
              <span>回收站</span>
            </el-menu-item>
          </el-menu>
        </el-aside>

        <!-- 主内容区 -->
        <el-main class="main-content">
          <div class="welcome-section">

            <div class="storage-info" v-if="storageInfo">
              <el-card>
                <template #header>
                  <span>存储空间</span>
                </template>
                <el-progress
                  :percentage="storageInfo.usagePercentage"
                  :color="getProgressColor(storageInfo.usagePercentage)"
                />
                <p class="storage-text">
                  已使用 {{ formatFileSize(storageInfo.usedStorage) }} /
                  {{ formatFileSize(storageInfo.totalStorage) }}
                </p>
              </el-card>
            </div>

            <div class="quick-actions">
              <el-button type="primary" size="large" @click="$router.push('/files')">
                <el-icon><Folder /></el-icon>
                管理文件
              </el-button>
              <el-button type="success" size="large" @click="$router.push('/share')">
                <el-icon><Share /></el-icon>
                我的分享
              </el-button>
            </div>
          </div>
        </el-main>
      </el-container>
    </el-container>

    <!-- 个人信息对话框 -->
    <UserProfileDialog v-model="showProfileDialog" />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/stores/user'
import { getStorageInfo } from '@/api/file'
import type { StorageInfo } from '@/api/file'
import UserProfileDialog from '@/components/UserProfileDialog.vue'
import {
  User,
  ArrowDown,
  Folder,
  Share,
  Delete,
  Upload
} from '@element-plus/icons-vue'

const router = useRouter()
const userStore = useUserStore()

const storageInfo = ref<StorageInfo | null>(null)
const showProfileDialog = ref(false)

// 处理用户菜单命令
const handleCommand = (command: string) => {
  switch (command) {
    case 'profile':
      showProfileDialog.value = true
      break
    case 'logout':
      userStore.logout()
      break
  }
}

// 格式化文件大小
const formatFileSize = (size: number | string | undefined): string => {
  const numSize = Number(size)

  // 处理无效数据
  if (isNaN(numSize) || numSize < 0) return '0 B'
  if (numSize === 0) return '0 B'

  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB', 'TB']
  const i = Math.floor(Math.log(numSize) / Math.log(k))

  // 确保索引在有效范围内
  const sizeIndex = Math.min(i, sizes.length - 1)
  const formattedSize = parseFloat((numSize / Math.pow(k, sizeIndex)).toFixed(2))

  return formattedSize + ' ' + sizes[sizeIndex]
}

// 获取进度条颜色
const getProgressColor = (percentage: number) => {
  if (percentage < 60) return '#67c23a'
  if (percentage < 80) return '#e6a23c'
  return '#f56c6c'
}

// 获取存储信息
const fetchStorageInfo = async () => {
  try {
    const rawStorageInfo = await getStorageInfo()

    // 数据验证和修复
    const totalStorage = Number(rawStorageInfo.totalStorage) || 0
    const usedStorage = Number(rawStorageInfo.usedStorage) || 0

    // 计算使用百分比
    let usagePercentage = 0
    if (totalStorage > 0) {
      usagePercentage = Math.round((usedStorage / totalStorage) * 100)
    }

    // 确保百分比在合理范围内
    usagePercentage = Math.max(0, Math.min(100, usagePercentage))

    storageInfo.value = {
      totalStorage,
      usedStorage,
      availableStorage: Math.max(0, totalStorage - usedStorage),
      usagePercentage
    }

    console.log('存储信息:', storageInfo.value)
  } catch (error) {
    console.error('获取存储信息失败:', error)
    // 设置默认存储信息
    storageInfo.value = {
      totalStorage: 10737418240, // 10GB 默认空间
      usedStorage: 0,
      availableStorage: 10737418240,
      usagePercentage: 0
    }
  }
}

onMounted(() => {
  // 获取用户信息
  if (userStore.isLoggedIn && !userStore.userInfo) {
    userStore.fetchUserInfo()
  }

  // 获取存储信息
  fetchStorageInfo()
})
</script>

<style scoped>
.home-container {
  height: 100vh;
  width: 100vw;
}

.el-container {
  height: 100%;
  width: 100%;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: #fff;
  border-bottom: 1px solid #e6e6e6;
  padding: 0 20px;
}

.header-left h2 {
  margin: 0;
  color: #409eff;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 5px;
  cursor: pointer;
  padding: 8px 12px;
  border-radius: 4px;
  transition: background-color 0.3s;
}

.user-info:hover {
  background-color: #f5f5f5;
}

.sidebar {
  background-color: #f5f5f5;
  border-right: 1px solid #e6e6e6;
}

.main-content {
  background: #f8f9fa;
}

.welcome-section {
  width: 100%;
  padding: 40px 20px;
  text-align: center;
}

.welcome-section h1 {
  font-size: 32px;
  color: #333;
  margin-bottom: 10px;
}

.welcome-section p {
  color: #666;
  font-size: 16px;
  margin-bottom: 40px;
}

.storage-info {
  margin-bottom: 40px;
  max-width: 500px;
  margin-left: auto;
  margin-right: auto;
}

.storage-text {
  margin-top: 10px;
  color: #666;
  font-size: 14px;
}

.quick-actions {
  display: flex;
  gap: 20px;
  justify-content: center;
}

.quick-actions .el-button {
  padding: 15px 30px;
}
</style>
